<template>
  <el-container style="height: 1200px; border: 1px solid #eee">
    <el-header>
      <div class="search-form">
        <el-row :gutter="20" class="search-style">
          <el-col :span="4">
            <label>系统</label>
            <el-select v-model="queryParam.system" value="DEMO" size="mini">
              <el-option key="DEMO" label="DEMO" value="DEMO"></el-option>
            </el-select>
          </el-col>
          <el-col :span="4">
            <label>事件</label>
            <el-input v-model="queryParam.eventType" value="" size="mini"></el-input>
          </el-col>
          <el-col :span="4">
            <label>聚合</label>
            <el-input v-model="queryParam.aggregateType" value="" size="mini"></el-input>
          </el-col>
          <el-col :span="6">
            <label>事件时间</label>
            <el-date-picker
              v-model="queryParam.eventTime"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="yyyy/MM/dd"
              value-format="yyyy-MM-dd HH:mm:ss"
              size="small">
            </el-date-picker>
          </el-col>
          <el-col :span="4">
            <label>事件触发人</label>
            <el-input v-model="queryParam.eventUser" value="" size="mini"></el-input>
          </el-col>
        </el-row>
        <el-row class="search-style">
          <el-col :span="22">
            <label>聚合内容</label>
            <el-input type="textarea" autosize v-model="queryParam.aggregate" value="" size="mini"></el-input>
          </el-col>
          <el-col :span="2">
            <el-button type="primary" @click="doQuery" size="mini">查询</el-button>
          </el-col>
        </el-row>
      </div>
    </el-header>
    <el-main style="margin: 50px 10px">
      <div style="width:100%;height:100%;">
        <svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" xml:space="preserve"
         width="1800" height="1000"> </svg>
      </div>
    </el-main>
  </el-container>
</template>

<script>
import * as d3 from 'd3';
export default {
  name: 'EventQuery',
  mounted:function(){
    this.showEventImg();
  },
  methods: {
    showEventImg: function(){
      for(var nodeIndex = 0; nodeIndex < this.nodes.length; nodeIndex++){
        if((parseInt(nodeIndex/5)+1)%2 === 1){
          this.nodes[nodeIndex]['x'] = 100+(4-nodeIndex%5)*400;
        }else{
          this.nodes[nodeIndex]['x'] = 100+nodeIndex%5*400;
        }
        this.nodes[nodeIndex]['y'] = parseInt(nodeIndex/5)*400+100;
      }
      var nodesCopy = JSON.parse(JSON.stringify(this.nodes));

      let simulation = d3.forceSimulation(this.nodes);

      let svg = d3.select('svg')
      let width = +svg.attr('width')
      let height = +svg.attr('height')

      simulation
        .force('center_force', d3.forceCenter(width / 2, height / 2))
        .force('charge_force', d3.forceManyBody())


      //箭头
      var marker=
          svg.append("marker")
          //.attr("id", function(d) { return d; })
          .attr("id", "resolved")
          //.attr("markerUnits","strokeWidth")//设置为strokeWidth箭头会随着线的粗细发生变化
          .attr("markerUnits","userSpaceOnUse")
          .attr("viewBox", "0 -5 10 10")//坐标系的区域
          .attr("refX",93)//箭头坐标
          .attr("refY", -1)
          .attr("markerWidth", 12)//标识的大小
          .attr("markerHeight", 12)
          .attr("orient", "auto")//绘制方向，可设定为：auto（自动确认方向）和 角度值
          .attr("stroke-width",2)//箭头宽度
          .append("path")
          .attr("d", "M0,-5L10,0L0,5")//箭头的路径
          .attr('fill','#000000');//箭头颜色

      //添加连线 
      var svg_edges = svg.selectAll("line")
        .data(this.edges)
        .enter()
        .append("line")
        .style("stroke","#ccc")
        .style("stroke-width",1)
        .attr("marker-end", "url(#resolved)");

      var color = d3.color("steelblue");

      //添加节点 
      var svg_nodes = svg.selectAll("circle")
        .data(this.nodes)
        .enter()
        .append("circle")
        .attr("r",100)
        .attr("class", "fixedNode")	
        .style("fill",function(d,i){
          return color;
        })
        .style('fill',function(node){
              return "#33CC00";
        });

      var dateFormate = function(timestamp){
        var date = new Date(timestamp); //获取一个时间对象
      
        ; // 获取完整的年份(4位,1970)
        ; // 获取月份(0-11,0代表1月,用的时候记得加上1)
        // 获取日(1-31)
        date.getTime(); // 获取时间(从1970.1.1开始的毫秒数)
        date.getHours(); // 获取小时数(0-23)
        date.getMinutes(); // 获取分钟数(0-59)
        date.getSeconds(); // 获取秒数(0-59)
        
        return date.getFullYear() + "-" + date.getMonth() + "-" + date.getDate() +
            " " + date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds();
      }

      //给圆圈加提示
      svg_nodes.append("svg:title")
        .text(function(note){
          return "事件: " + note.eventType + "\n" +
                "聚合: " + note.aggregateType + "\n" +
              "时间: " + dateFormate(note.eventTime) + "\n";
        });

      //圆圈文字
      var svg_texts = svg.append("g").selectAll("text")
        .data(this.nodes)
        .enter()
        .append("text")
        .attr("dy", ".35em")
        .attr("text-anchor", "middle")
        .text(function(note){
          return note.eventType;
        });

      simulation.on("tick", function(){ //对于每一个时间间隔
          
        //更新节点坐标
          svg_nodes.attr("cx",function(d){
            return nodesCopy[d.index].x;
          })
          .attr("cy",function(d){return nodesCopy[d.index].y;});	

        
        //更新连线坐标
          svg_edges.attr("x1",function(d){ 
            return nodesCopy[d.source].x; 
            })	
            .attr("y1",function(d){ return nodesCopy[d.source].y; })
            .attr("x2",function(d){ return nodesCopy[d.target].x; })
            .attr("y2",function(d){ return nodesCopy[d.target].y; });
              
        //更新文字坐标
        svg_texts.attr("x", function(d){ return nodesCopy[d.index].x; })
            .attr("y", function(d){ return nodesCopy[d.index].y; });
      });
    },
    dragstart: function(d) {
      if(!d3.event.active){
        force.alphaTarget(.1).restart();
      }
      d.fx = d.x;
      d.fy = d.y;
    },
    dragged: function(d){
      d.fx = d3.event.x;
      d.fy = d3.event.y;
    },
    dragended: function(d){
      // force.stop();
      if(!d3.event.active){
        force.alphaTarget(0);
      }
      d.fx = null;
      d.fy = null;
    }
  },
  data() {
    return {
      msg: 'Event Query',
      queryParam: {
        system: '',
        eventType: '',
        aggregateType: '',
        eventTime: [],
        eventUser: '',
        aggregate: ''
      },
      nodes: [
        {id:1, eventType:"AA", aggregateType:"UserAggr",eventTime:1632116548000},
        {id:1, eventType:"UserCreatedEvent", aggregateType:"UserAggr",eventTime:1632116548000},
        {id:1, eventType:"UserCreatedEvent", aggregateType:"UserAggr",eventTime:1632116548000},
        {id:1, eventType:"UserCreatedEvent", aggregateType:"UserAggr",eventTime:1632116548000},
        {id:1, eventType:"UserCreatedEvent", aggregateType:"UserAggr",eventTime:1632116548000},
        {id:1, eventType:"UserCreatedEvent", aggregateType:"UserAggr",eventTime:1632116548000},
        {id:1, eventType:"UserCreatedEvent", aggregateType:"UserAggr",eventTime:1632116548000},
        {id:1, eventType:"UserCreatedEvent", aggregateType:"UserAggr",eventTime:1632116548000},
        {id:2, eventType:"RoleCreatedEvent", aggregateType:"RoleAggr",eventTime:1632116549000}
      ],
      edges : [
        {source: 1, target: 0},
        {source: 2, target: 1},
        {source: 3, target: 2},
        {source: 4, target: 3},
        {source: 5, target: 4},
        {source: 6, target: 5},
        {source: 7, target: 6},
        {source: 8, target: 7},
      ]
    }
  }
}
</script>

<style type="text/css" scoped lang="scss">

.vertical {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.search-form {
  border-top: 1px solid #d5d5d5;

  .search-style {
    margin: 11px 0 11px 8px !important;
  }
}
</style>
